// pages/mch/car/edit.js
const App = getApp()
import Util from '../../../utils/util'
import Qiniu from '../../../utils/qiniu'

Page({
  data: {
    init: false,
    loading: false,
    activeNames: ['1'],

    mer: {},
    conf: {},
    car: {},

    colors: [],

    vlca: '',
    photo: [],
    sid: '',
    name: '',
    cno: '',
    vin: '',
    eno: '',
    attr_color: '',
    attr_year: new Date().getFullYear(),
    attr_liter: '',
    attr_seat: 0,
    attr_door: 0,
    attr_gearauto: true,
    price_pdp: 0,
    price_pmp: 0,
    price_mdp: 0,
    price_deposit: 0,
    price_disp: 0,
    settle_type: 1,
    settle_rent_base_amt: 0,
    settle_rent_base_uid: '',
    settle_rent_base_name: '',
    settle_rent_spliter: [],
    settle_rate_spliter: [],
    service_onsite_flag: false,
    service_remote_flag: false,
    service_bins_flag: false,
    service_dins_flag: false,
    service_tins_flag: false,
    service_free_flag: false,
    service_night_flag: false,
    service_waive_flag: false,

    settle_show: true,
    service_show: false,
  },
  onLoad(options) {
    App.doPost({
      uri: '/app/merchant/conf/detail',
      body: {},
      fnSucc: resp => {
        this.setData({
          mer: resp.data,
          conf: resp.data.city,
        })
        this.execLoad(options.cid)
      },

    })
  },
  doHide() {
    Util.Dialog.confirm(`是否下架车辆[${this.data.car.cno}]?`, () => {
      App.doPost({
        uri: '/app/merchant/car/show/set',
        body: {
          id: this.data.car.id,
          show: false
        },
        fnSucc: () => {
          wx.pub("ReloadCarList", {})

          this.execLoad(this.data.car.id)
        }
      })
    })
  },
  onChange(event) {
    console.log(event)
    this.setData({
      activeNames: event.detail,
      settle_show: event.detail.findIndex(d => d == "1") >= 0,
      service_show: event.detail.findIndex(d => d == "2") >= 0,
    });
  },
  execLoad(cid) {
    App.doPost({
      uri: '/app/merchant/car/detail',
      body: {
        id: cid
      },
      fnSucc: resp => {
        this.setData({
          init: true,
          car: resp.data,

          vlca: resp.data.vlc.pica,
          photo: resp.data.photo,
          sid: resp.data.sid,
          name: resp.data.name,
          cno: resp.data.cno,
          vin: resp.data.vin,
          eno: resp.data.eno,
          attr_color: resp.data.attr.color,
          attr_year: resp.data.attr.year,
          attr_liter: resp.data.attr.liter,
          attr_seat: resp.data.attr.seat,
          attr_door: resp.data.attr.door,
          attr_gearauto: resp.data.attr.gearauto,
          price_pdp: resp.data.price.pdp / 100,
          price_pmp: resp.data.price.pmp / 100,
          price_mdp: resp.data.price.mdp / 100,
          price_deposit: resp.data.price.deposit / 100,
          price_disp: resp.data.price.disp / 100,
          settle_type: 1, //resp.data.settle.type,
          settle_rent_base_amt: resp.data.settle.rent.base.amt / 100,
          settle_rent_base_uid: resp.data.settle.rent.base.uid,
          settle_rent_base_name: resp.data.settle.rent.base.name,
          settle_rent_spliter: resp.data.settle.rent.spliter.map(s => {
            return {
              amt: s.amt / 100,
              rate: s.rate / 10,
              uid: s.uid,
              name: s.name,
              type: s.type,
              sort: s.sort
            }
          }),
          settle_rate_spliter: resp.data.settle.rate.spliter.map(s => {
            return {
              rate: s.rate / 10,
              uid: s.uid,
              name: s.name,
              sort: s.sort
            }
          }),
          service_onsite_flag: resp.data.service.onsite.flag,
          service_remote_flag: resp.data.service.remote.flag,
          service_bins_flag: resp.data.service.bins.flag,
          service_dins_flag: resp.data.service.dins.flag,
          service_tins_flag: resp.data.service.tins.flag,
          service_free_flag: resp.data.service.free.flag,
          service_night_flag: resp.data.service.night.flag,
          service_waive_flag: resp.data.service.waive.flag,
        })
      }
    })
  },
  doSelectUser() {
    let amt = true
    let rate = true
    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_uid == '') {
        rate = false
      }
    } else {
      amt = false
    }
    wx.navigateTo({
      url: `/pages/mch/car/user?type=${this.data.settle_type}&amt=${amt}&rate=${rate}`,
      events: {
        enter: (seld) => {
          console.log(seld)
          if (this.data.settle_type == 2) {
            if (this.data.settle_rent_base_uid == '') {
              this.setData({
                settle_rent_base_amt: parseFloat(seld.amt),
                settle_rent_base_uid: seld.uid,
                settle_rent_base_name: seld.name,
              })
            } else {
              let spliter = this.data.settle_rent_spliter
              spliter[spliter.length] = {
                uid: seld.uid,
                name: seld.name,
                type: seld.type,
                amt: parseFloat(seld.amt),
                rate: parseFloat(seld.rate),
              }
              let idx = 1
              spliter.forEach(s => {
                s.sort = s.uid == 'share' ? 99999 : idx++
              })
              spliter.sort((m, n) => {
                return m.sort - n.sort
              })

              this.setData({
                settle_rent_spliter: spliter
              })
            }
          } else {
            let spliter = this.data.settle_rate_spliter
            spliter[spliter.length] = {
              uid: seld.uid,
              name: seld.name,
              rate: parseFloat(seld.rate),
            }
            this.setData({
              settle_rate_spliter: spliter
            })
          }

        }
      }
    })
  },
  doDelRentSpliter() {
    let spliter = this.data.settle_rent_spliter
    if (spliter.length > 0) {
      spliter.length = spliter.length - 1
      this.setData({
        settle_rent_spliter: spliter
      })
    } else {
      this.setData({
        settle_rent_base_amt: 0,
        settle_rent_base_uid: '',
        settle_rent_base_name: '',
      })
    }
  },
  doDelRateSpliter() {
    let spliter = this.data.settle_rate_spliter
    if (spliter.length > 0) {
      spliter.length = spliter.length - 1
      this.setData({
        settle_rate_spliter: spliter
      })
    }
  },
  doSettleChange(e) {
    this.setData({
      settle_type: parseInt(e.currentTarget.dataset.type)
    })
  },
  doCheckInput(e) {
    let value = parseFloat(e.detail.value || '0')
    let min = parseFloat(e.target.dataset.min || '0')
    let max = parseFloat(e.target.dataset.max || '99999')
    if (value < min) {
      return min + ''
    }
    if (value > max) {
      return max + ''
    }
    return parseFloat(value.toFixed(2)) + ''
  },
  doSaveConfig() {
    if (parseInt(this.data.price_mdp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`终端价格不得低于同行价格`)
      return
    }
    if (parseInt(this.data.price_pmp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`同行月租价格不得低于日租价格`)
      return
    }
    if (parseInt(this.data.price_deposit * 100) <= 2000 * 100) {
      Util.Notify.warn(`车辆押金不得低于违章押金2000元`)
      return
    }

    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_amt <= 0 || this.data.settle_rent_base_uid == '') {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    if (this.data.settle_type == 3) {
      if (this.data.settle_rate_spliter.length <= 0) {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    let i = 1
    let rent_spliter = this.data.settle_rent_spliter.map(spliter => {
      return {
        amt: parseInt(spliter.amt * 100),
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        type: spliter.type,
        sort: i++,
      }
    })

    let k = 1
    let rate_spliter = this.data.settle_rate_spliter.map(spliter => {
      return {
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        sort: k++,
      }
    })
    if (this.data.settle_type == 3) {
      let max = rate_spliter.reduce((p, c) => p + c.rate, 0)
      if (max != 1000) {
        Util.Notify.warn(`请设置正确的租金分配比例`)
        return
      }
    }

    this.setData({
      loading: true
    })
    const params = {
      id: this.data.car.id,
      service: {
        onsite: {
          flag: this.data.service_onsite_flag && this.data.conf.service.onsite.flag && this.data.mer.service.onsite.flag
        },
        remote: {
          flag: this.data.service_remote_flag && this.data.conf.service.remote.flag && this.data.mer.service.remote.flag
        },
        bins: {
          flag: this.data.service_bins_flag && this.data.conf.service.bins.flag && this.data.mer.service.bins.flag
        },
        dins: {
          flag: this.data.service_dins_flag && this.data.conf.service.dins.flag && this.data.mer.service.dins.flag
        },
        tins: {
          flag: this.data.service_tins_flag && this.data.conf.service.tins.flag && this.data.mer.service.tins.flag
        },
        free: {
          flag: this.data.service_free_flag && this.data.conf.service.free.flag && this.data.mer.service.free.flag
        },
        night: {
          flag: this.data.service_night_flag && this.data.conf.service.night.flag && this.data.mer.service.night.flag
        },
        waive: {
          flag: this.data.service_waive_flag && this.data.conf.service.waive.flag && this.data.mer.service.waive.flag
        }
      },
      price: {
        pdp: parseInt(this.data.price_pdp * 100),
        pmp: parseInt(this.data.price_pmp * 100),
        mdp: parseInt(this.data.price_mdp * 100),
        deposit: parseInt(this.data.price_deposit * 100),
        disp: parseInt(this.data.price_disp * 100)
      },
      settle: {
        type: this.data.settle_type,
        rent: {
          base: {
            amt: parseInt(this.data.settle_rent_base_amt * 100),
            uid: this.data.settle_rent_base_uid
          },
          spliter: rent_spliter
        },
        rate: {
          spliter: rate_spliter
        }
      },
      // cover: "123123"
      photo: this.data.photo,
    }
    console.log('params', params)
    App.doPost({
      uri: '/app/merchant/car/update',
      body: params,
      fnSucc: () => {
        wx.pub("ReloadCarList", {})
        Util.Toast.succ(`提交成功`)
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000);
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  doPreviewItem(e) {
    let sources = []
    const index = e.currentTarget.dataset.index
    this.data.photo.forEach(p => {
      sources[sources.length] = {
        url: p,
        type: 'image'
      }
    })

    wx.previewMedia({
      sources: sources,
      current: index
    })
  },
  doDeleteItem(e) {
    const index = e.currentTarget.dataset.index
    let photo = JSON.parse(JSON.stringify(this.data.photo))
    photo.splice(index, 1)
    this.setData({
      photo: photo
    })
  },
  doChooseItem(e) {
    wx.chooseMedia({
      count: 9 - this.data.photo.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        // this.execUpload(res.tempFiles[0].tempFilePath)
        const uploadFun = async ()=>{
          for (let index = 0; index < res.tempFiles.length; index++) {
            const element = res.tempFiles[index];
            await this.execUpload(element.tempFilePath)
          }
        }
        uploadFun()
      }
    })
  },
  execUpload(path) {
    return new Promise((resolve, reject)=>{
      App.doPost({
        uri: '/comm/tool/file/qiniu/info',
        body: {
          type: 'Image'
        },
        fnSucc: resp => {
          let key = resp.data.path + resp.data.fileid + '.' + path.split('.').pop()?.toLowerCase()
          Qiniu.upload(path, (res) => {
            let photo = this.data.photo
            photo[photo.length] = res.imageURL
            this.setData({
              photo: photo
            })
            resolve(null)
          }, (err) => {
            console.log(err)
            resolve(null)
          }, {
            region: 'NCN',
            key: key,
            uptoken: resp.data.token,
            uptokenFunc: null,
            uptokenURL: null,
            domain: resp.data.domain,
            shouldUseQiniuFileName: false,
          }, () => {
  
          }, () => {
  
          })
        },
        fnFail: resp => {
          App.doAlert('出错啦', `上传失败，[${resp.stat.err}] ${resp.stat.msg}`)
          resolve(null)
        }
      })
    })
  },
})